package com.qf.Interceptor;

import com.alibaba.fastjson.JSON;
import org.jctools.maps.NonBlockingHashMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

public class UploadExcelInterceptor implements HandlerInterceptor {
    @Value("${uploadExcelSize}")
    private Long size;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String reg = "\\.xls$";


        NonBlockingHashMap<String,Object> map = new NonBlockingHashMap<>();


        boolean suffixFalse=false;


        if(request instanceof DefaultMultipartHttpServletRequest) {
            // 677139577
            DefaultMultipartHttpServletRequest req = (DefaultMultipartHttpServletRequest)request;

            long size = req.getContentLengthLong(); //获取文件的大小
            System.out.println(size);
            //获取所有文件
            MultiValueMap<String, MultipartFile> multiFileMap = req.getMultiFileMap();
            Set<Map.Entry<String, List<MultipartFile>>> entries = multiFileMap.entrySet();
//            遍历所有文件,判断文件格式是否符合
            for (Map.Entry<String, List<MultipartFile>> mapEntry: entries) {
                List<MultipartFile> value = mapEntry.getValue();
                for (MultipartFile multi:value) {
                    if (!Pattern.matches(reg,multi.getOriginalFilename())){
                        map.put("code",0);
                        map.put("msg","文件类型不符合！！！");

                        responseMsg(response, map);
                        suffixFalse=true;

                    }
                }
            }
            if (suffixFalse){
                return false;
            }else if(size > this.size) {
                map.put("code",0);
                map.put("msg","文件超过了1G");
                responseMsg(response, map);
                return false;
            }
            return true;
        }else {  // 如果改请求不是一个多媒体的请求的， 那么表示用户不是按照常规的方式来请求上传的
            return false;
        }
    }

    public void responseMsg(HttpServletResponse response, NonBlockingHashMap<String, Object> map) {
        PrintWriter writer=null;
        try {
            writer= response.getWriter();

            writer.write(JSON.toJSONString(map));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (writer!=null){
                writer.close();
            }
        }
    }
}
